<script src="{{chat_server}}/socket.io/socket.io.js"></script>
   <style>
      #chat {
      position: fixed;
      right: 0;
      bottom: 30px;
      padding: 20px;
      font-family: monospace;
      width: 300px;
      z-index: 100;
      background-color: black;
      opacity: .4;
      color: white;
      overflow-y: auto;
      }
      #chat input {
      font-size: inherit;
      font-family: inherit;
      width: 100%;
      margin-top: 5px;
      }
      #chat .message {
      margin-top: 5px;
      }
      #chat .message .user {
      display: inline;
      margin-right: 0.8em;
      font-weight: bold;
      }
      #chat .message .text {
      display: inline;
      word-wrap: break-word;
      }
   </style>
   <!-- HTML layout for the chat window -->
   <div id = "chat" style="display:none">
      <h3 id = "chat_title">Lobby</h3>
      <div id="messages"></div>
      <input id="message" placeholder="Message"/>
   </div>

   <script>
      // If documentID exists, that means you should open two chat sessions.
      var documentID = "{{documentid}}";
      if(documentID!=""){
         // $('#chat_title').html("Chat - {{filename}}")
         var socket{{documentid}} = io.connect('{{chat_server}}');
      }else{
         var socket{{documentid}} = io.connect('{{chat_server}}');
      }

      // Blinky Chat Button for notification.
   	function blinks(selector){
   	  	for (var i=0; i < 5; i++){
   	  		$(selector).fadeOut('slow', function(){
   	  			$(this).fadeIn('slow');
   	  		});
   		}
   	}

      // IN DEV: Request server for a namespace and connect to that namespace.
      socket{{documentid}}.emit('requestNs', {'docID': documentID}, function(data){
         socket{{documentid}} = io.connect('{{chat_server}}'+data.namespace)
      });
      
      // If socket receives a new message from server, change the button for notification.  
      socket{{documentid}}.on('msg', function(data){
      	var msg = JSON.parse(data);
      	$('#chatnotification').attr('class', 'btn btn-warning');
         $('#chatnotification').html('<i class="icon-envelope icon-white"></i>  New Message');
      	blinks('#chatnotification');
      	addChatMessage(msg);
      });
      
      socket{{documentid}}.on('init', function(data){
      	var messages = JSON.parse(data)
      	for(i in messages)
      		addChatMessage(messages[i]);
      })
      
      $('#message').keydown(function (e) {
      if ((e.keyCode || e.which) == 13) {
      if (!e.target.value) return;
      // enter was pressed
      
               var msg = {};
               msg['username'] = '{{ user.username }}';
               msg['message'] = $('#message').val();
      
               addChatMessage(msg);
               socket{{documentid}}.emit('msg', JSON.stringify(msg));
      e.target.value = '';
      }
      });
      
         // IN DEV: MORE IDENTIFIBLE USER NAME COLOR
         // function hslToRgb(h, s, l){
         //    var r, g, b;

         //    if(s == 0){
         //       r = g = b = l; // achromatic
         //    } else {
         //       function hue2rgb(p, q, t) {
         //          if(t < 0) t += 1;
         //          if(t > 1) t -= 1;
         //          if(t < 1/6) return p + (q - p) * 6 * t;
         //          if(t < 1/2) return q;
         //          if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
         //          return p;
         //       }

         //       var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
         //       var p = 2 * l - q;
         //       r = hue2rgb(p, q, h + 1/3);
         //       g = hue2rgb(p, q, h);
         //       b = hue2rgb(p, q, h - 1/3);
         //    }

         //    return '#' + Math.round(r * 255).toString(16) + Math.round(g * 255).toString(16) + Math.round(b * 255).toString(16);
         // };

         // function colorForName(name) {
         //    var x = 0;
         //    var p = 31;
         //    for (var i = 0; i < name.length; i++) {
         //       var c = name.charCodeAt(i);
         //       x += c * p;
         //       p *= p;
         //       x = x % 4294967295;
         //    }
         //    var h = (x % 89)/89;
         //    var color = hslToRgb(h, 0.7, 0.3)
         //    return color;
         // }
      // Add a chat message to the chat window.
      function addChatMessage(m) {
      var msg = $('<div class="message"><div class="user"></div><p class="text"></p></div>');
      $('.text', msg).text(m['message']);
      
      $('.user', msg).text(m['username']);
      $('.user', msg).css('color', 'white');
      $('#chat #messages').append(msg);
      var allMsgs = $('.message')
      if (allMsgs.length > 15) {
      allMsgs.slice(0, Math.max(0,allMsgs.length - 15)).each(function () {
      	var e = $(this);
      	e.fadeOut('slow', function () {
      		e.remove();
      	});
      });
      }
      }
      
   </script>

